package springboot.demo.filter;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import springboot.demo.annotation.NotProfile;
import springboot.demo.service.impl.UserDetailsServiceImpl;
import springboot.demo.util.JwtUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 * 用于处理请求中的JWT令牌，实现无状态认证
 */
@Component
@NotProfile("simple")
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    /**
     * JWT工具类，用于处理token的生成和验证
     */
    private final JwtUtil jwtUtil;

    /**
     * 用户详情服务，用于加载用户信息
     */
    private final UserDetailsServiceImpl userDetailsService;

    /**
     * 构造函数注入依赖
     * @param jwtUtil JWT工具类
     * @param userDetailsService 用户详情服务
     */
    public JwtAuthenticationFilter(JwtUtil jwtUtil, UserDetailsServiceImpl userDetailsService) {
        this.jwtUtil = jwtUtil;
        this.userDetailsService = userDetailsService;
    }

    /**
     * 过滤器的主要处理逻辑
     * 1. 从请求头中提取token
     * 2. 验证token的有效性
     * 3. 设置认证信息到SecurityContext
     *
     * @param request HTTP请求
     * @param response HTTP响应
     * @param filterChain 过滤器链
     * @throws ServletException Servlet异常
     * @throws IOException IO异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 从请求头中获取Authorization
        final String authHeader = request.getHeader("Authorization");
        final String jwt;
        final String username;

        // 如果请求头中没有token或格式不正确，直接放行
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 提取token（去掉"Bearer "前缀）
        jwt = authHeader.substring(7);
        // 从token中提取用户名
        username = jwtUtil.extractUsername(jwt);

        // 如果成功提取到用户名且当前没有认证信息
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 加载用户详情
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            // 验证token
            if (jwtUtil.validateToken(jwt, userDetails)) {
                // 创建认证令牌
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userDetails,
                        null,
                        userDetails.getAuthorities()
                );
                // 设置认证详情
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 将认证信息设置到SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }
        // 继续过滤器链
        filterChain.doFilter(request, response);
    }
} 